<template>
	<div class="table-wrapper">
		<div class="operate-wrapper">
			<template v-if="showImportBtnGroup">
				<el-button
					class="template"
					:disabled="loading"
					size="medium"
					@click="openImportDialog"
				>
					{{ $t('common.components.import') }}
				</el-button>
				<el-button
					class="template"
					:disabled="loading"
					size="medium"
					@click="openSaveDialog"
				>
					{{ $t('common.components.save_as_template') }}
				</el-button>
			</template>

			<el-button
				class="add"
				icon="el-icon-folder"
				type="warning"
				:disabled="loading || template.loading"
				size="medium"
				@click="addRow"
			>
				{{ $t('common.add') }}
			</el-button>
		</div>
		<el-form
			ref="tableForm"
			:inline="false"
			size="normal"
			:model="{ tableForm }"
		>
			<el-table
				v-loading="loading"
				element-loading-spinner="el-icon-loading"
				border
				size="mini"
				:header-cell-style="getRowClass"
				:data="tableForm"
			>
				<el-table-column
					align="center"
					type="index"
					:width="getWidth('50px', 1.3)"
					:label="$t('common.serial_number')"
				/>
				<el-table-column
					align="center"
					:label="contractRatioName + '(%)'"
					:prop="rebateRateFieldName"
				>
					<template slot-scope="scope">
						<el-form-item
							v-if="customForm"
							:key="scope.$index"
							:class="'selc'"
							:prop="
								`tableForm.${
									scope.$index
								}.${rebateRateFieldName}`
							"
							:rules="[
								{
									required: true,
									validator: validateTableForm(
										rebateRateFieldName,
										contractRatioName,
										scope.$index
									),
									trigger: ['blur', 'change']
								}
							]"
						>
							<el-input-number
								v-model.trim="scope.row[rebateRateFieldName]"
								size="normal"
								:min="minCustomRatio"
								:controls="false"
								:placeholder="customRatioPlaceholder"
								style="width: 80%"
								:precision="2"
							/>
						</el-form-item>

						<el-form-item
							v-else
							:class="'selc'"
							:prop="
								`tableForm.${
									scope.$index
								}.${rebateRateFieldName}`
							"
							:rules="[
								{
									required: true,
									validator: validateRebate(
										contractRatioName,
										scope.$index
									),
									trigger: 'change'
								}
							]"
						>
							<el-select
								v-model.trim="scope.row[rebateRateFieldName]"
								@change="onSelected($event, scope.$index)"
							>
								<el-option
									v-for="item in rebateRatioList"
									:key="item.id"
									:label="item.rebateRatio"
									:value="item.rebateRatio"
									:disabled="item.disabled"
								></el-option>
							</el-select>
						</el-form-item>
					</template>
				</el-table-column>
				<el-table-column
					v-for="(item, index) in tableColumnConfig.columns"
					:key="index"
					align="center"
					:label="
						item.label +
							`(${
								item.prop === 'gameLoss' ||
								item.prop === 'gameFlow' ||
								item.prop === 'validBetAmount' ||
								item.prop === 'netAmount'
									? currencySymbol
									: item.suffix
							})`
					"
					:prop="item.prop"
				>
					<template slot-scope="scope">
						<el-form-item
							:key="scope.$index"
							:class="'cl' + scope.$index"
							:prop="`tableForm.${scope.$index}.${item.prop}`"
							:rules="[
								{
									required: true,
									validator: validateTableForm(
										item.prop,
										item.label,
										scope.$index
									),
									trigger: ['blur', 'change']
								}
							]"
						>
							≥
							<el-input-number
								v-model.trim="scope.row[item.prop]"
								size="normal"
								:min="item.input.min"
								:max="item.input.max"
								:controls="false"
								style="width: 80%"
								:precision="item.input.precision"
							/>
						</el-form-item>
					</template>
				</el-table-column>
				<el-table-column
					prop="operating"
					align="center"
					:label="$t('common.actions')"
					width="120"
				>
					<template slot-scope="scope">
						<el-button
							type="danger"
							icon="el-icon-delete"
							size="medium"
							@click="
								deleteRow(
									scope.$index,
									'commissionContractList'
								)
							"
						>
							{{ $t('common.delete') }}
						</el-button>
					</template>
				</el-table-column>
			</el-table>
		</el-form>

		<el-dialog
			:title="$t('common.components.import')"
			:visible.sync="template.importDialog"
			:modal-append-to-body="false"
			append-to-body
			top="20vh"
			@close="closeDialog('importTemplate')"
		>
			<el-form
				ref="importTemplate"
				v-loading="template.loading"
				:model="template.importFormData"
				:inline="false"
				size="normal"
				:rules="dialogRules.importFormData"
			>
				<el-form-item
					:label="`${$t('common.components.template_type')}:`"
					prop="type"
				>
					<el-input
						:value="contractName"
						style="width: 80%"
						disabled
					/>
				</el-form-item>
				<el-form-item
					:label="`${$t('common.components.policy_type')}:`"
					:rules="[
						{
							required: true,
							message: $t(
								'common.components.policy_type_no_empty'
							),
							trigger: 'blur'
						}
					]"
				>
					<el-input
						:value="topForm.policyType.policyType"
						style="width: 80%"
						disabled
					/>
				</el-form-item>
				<el-form-item
					:label="`${$t('common.components.template_name')}:`"
					prop="templateId"
				>
					<el-select
						v-model.trim="template.importFormData.templateId"
						style="width: 80%"
						filterable
						:placeholder="$t('common.components.template_select')"
					>
						<el-option
							v-for="item in template.templateArr"
							:key="item.id"
							:label="item.templateName"
							:value="item.id"
						/>
						<el-pagination
							:current-page.sync="template.paginate.pageNum"
							background
							style="padding: 10px 20px 0"
							class="details-page"
							layout="total,prev, pager, next"
							:page-size="template.paginate.pageSize"
							:page-sizes="template.paginate.pageSizes"
							:total="template.paginate.total"
							@current-change="_handleCurrentChange"
							@size-change="_handleSizeChange"
						/>
					</el-select>
				</el-form-item>
			</el-form>
			<span slot="footer">
				<el-button @click="template.importDialog = false">
					{{ $t('common.cancel') }}
				</el-button>
				<el-button
					type="primary"
					:disabled="template.loading"
					@click="importTemplate"
				>
					<i v-show="template.loading" class="el-icon-loading" />
					<span>{{ $t('common.import') }}</span>
				</el-button>
			</span>
		</el-dialog>

		<el-dialog
			:title="$t('common.components.save_as_template')"
			:visible.sync="template.saveDialog"
			:modal-append-to-body="false"
			append-to-body
			:width="getWidth('500px')"
			top="20vh"
			@close="closeDialog('saveTemplate')"
		>
			<el-form
				ref="saveTemplate"
				:model="template.saveFormData"
				label-width="auto"
				:inline="false"
				size="normal"
				:rules="dialogRules.saveFormData"
			>
				<el-form-item
					:label="$t('common.components.template_type')"
					prop="templateType"
				>
					<el-input
						:value="
							contractType == 1
								? $t('common.components.commission')
								: $t('common.components.rebate')
						"
						style="width: 80%"
						disabled
					/>
				</el-form-item>
				<el-form-item
					:label="$t('common.components.policy_type')"
					:rules="[
						{
							required: true,
							message: $t(
								'common.components.policy_type_no_empty'
							),
							trigger: 'blur'
						}
					]"
				>
					<el-input
						:value="topForm.policyType.policyType"
						style="width: 80%"
						disabled
					/>
				</el-form-item>
				<el-form-item
					:label="$t('common.components.template_name')"
					prop="templateName"
				>
					<el-input
						v-model.trim="template.saveFormData.templateName"
						style="width: 80%"
						:maxlength="20"
						:placeholder="$t('common.components.input_name')"
					/>
				</el-form-item>
				<el-form-item
					:label="$t('common.components.template_decription')"
					prop="templateDes"
				>
					<el-input
						v-model.trim="template.saveFormData.templateDes"
						type="textarea"
						:maxlength="50"
						show-word-limit
						:placeholder="$t('common.components.input_description')"
						style="width: 80%"
					/>
				</el-form-item>
			</el-form>
			<span slot="footer">
				<el-button @click="template.saveDialog = false">
					{{ $t('common.cancel') }}
				</el-button>
				<el-button
					type="primary"
					:disabled="template.loading"
					@click="saveTemplate"
				>
					<i v-show="template.loading" class="el-icon-loading" />
					<span>{{ $t('common.save') }}</span>
				</el-button>
			</span>
		</el-dialog>
	</div>
</template>

<script>
import columnConfig from './columnConfig'
import templateData from './templateData'
import { Decimal } from 'decimal.js'
import { mapGetters } from 'vuex'

export default {
	props: {
		rebateRateFieldName: {
			type: String,
			default: () => 'rebateRate'
		},
		editContractList: {
			type: Array,
			default: () => []
		},
		topForm: {
			type: Object,
			default: () => {}
		},
		columnConfig: {
			type: Object,
			default: () => columnConfig
		},
		templateData: {
			type: Object,
			default: () => templateData
		},
		customForm: {
			type: Boolean,
			default: () => false
		},
		contractType: {
			type: Number,
			default: () => 1
		},
		border: {
			type: Boolean,
			default: () => false
		},
		showIndex: {
			type: Boolean,
			default: () => false
		},
		showSelection: {
			type: Boolean,
			default: () => false
		},
		showOperation: {
			type: Boolean,
			default: () => false
		},
		align: {
			type: String,
			default: () => 'center'
		},
		isEdit: {
			type: Boolean,
			default: () => false
		},
		showImportBtnGroup: {
			type: Boolean,
			default: () => false
		},
		loading: {
			type: Boolean,
			default: () => false
		}
	},

	data() {
		return {
			// 导入保存dialog
			template: {
				loading: false,
				templateArr: [],
				paginate: {
					total: 0,
					pageNum: 1,
					pageSize: 100,
					pageSizes: [10, 20, 50, 100, 200]
				},
				importDialog: false,
				importFormData: {
					templateId: undefined,
					type: this.$t('common.components.commission')
				},

				saveDialog: false,
				saveFormData: {
					templateType: this.$t('common.components.commission'),
					templateName: undefined,
					templateDes: undefined
				}
			},
			// 最低契约条件集合
			rebateRatioList: [],
			parentMaxRebateRate: 0,
			tableForm: [],
			// 自定义输入比例最小值
			minCustomRatio: 0.01
		}
	},

	computed: {
		...mapGetters(['merchantList', 'merchantInfo']),
		currencySymbol() {
			const merchantId =
				this.topForm.merchantId || this.topForm.policyType.merchantId
			const merchantInfo = this.merchantList.find(
				(item) => item.id === merchantId
			)
			return merchantInfo ? merchantInfo.currencySymbol : '¥'
		},
		customRatioPlaceholder() {
			let placeholder = ''
			if (this.minCustomRatio === this.maxCustomRatio) {
				placeholder = `${this.minCustomRatio}`
			} else {
				placeholder = `${this.minCustomRatio}~${this.maxCustomRatio}`
			}
			return placeholder
		},
		// 自定义输入比例最大值
		maxCustomRatio() {
			let maxRatio = 100
			if (this.topForm?.signProxyLevel > 0) {
				maxRatio = this._decimalToMul(this.parentMaxRebateRate)
			}
			return maxRatio
		},

		getTableForm() {
			return this.editContractList
				? JSON.parse(JSON.stringify(this.editContractList))
				: []
		},
		tableColumnConfig() {
			return this.columnConfig[this.contractType]
		},
		contractName() {
			const nameList = {
				1: this.$t('common.components.rebate1'),
				2: this.$t('common.components.rebate')
			}
			return nameList[this.contractType]
		},
		contractRatioName() {
			const nameList = {
				1: this.$t('agent.rebate_rate'),
				2: this.$t('funds.fund_audit.rebate_rate')
			}
			return nameList[this.contractType]
		},
		// rules() {},
		dialogRules() {
			return {
				importFormData: {
					templateId: [
						{
							required: true,
							message: this.$t(
								'common.components.select_template'
							),
							trigger: ['change']
						}
					],
					policyTypeConfigId: [
						{
							required: true,
							message: this.$t(
								'common.components.policy_type_no_empty'
							),
							trigger: 'blur'
						}
					],
					type: [
						{
							required: true,
							message: this.$t(
								'common.components.template_no_empty'
							),
							trigger: 'blur'
						}
					]
				},
				saveFormData: {
					templateName: [
						{
							required: true,
							message: this.$t(
								'common.components.input_template_name'
							),
							trigger: 'blur'
						}
					],
					templateType: [
						{
							required: true,
							message: this.$t(
								'common.components.template_no_empty'
							),
							trigger: 'blur'
						}
					],
					templateDes: [
						{
							required: true,
							message: this.$t(
								'common.components.description_no_empty'
							),
							trigger: 'blur'
						},
						{
							min: 2,
							max: 50,
							message: this.$t('common.components.limit_50'),
							trigger: 'blur'
						}
					]
				}
			}
		}
	},
	watch: {
		getTableForm(val) {
			this.tableForm = val
		}
	},
	created() {
		// !this.customForm && this.getRebateRatioList()
	},
	methods: {
		// matchsuffix(item) {
		// 	if (item.prop === 'netAmount' || item.prop === 'validBetAmount') {
		// 		return this.currencySymbol
		// 	} else {
		// 		return item.suffix
		// 	}
		// },
		onCustomRebateRateBlur(row) {
			if (
				!row[this.rebateRateFieldName] &&
				row[this.rebateRateFieldName] !== 0
			) {
				return (row[this.rebateRateFieldName] = undefined)
			}

			row[this.rebateRateFieldName] = new Decimal(
				new Decimal(row[this.rebateRateFieldName]).toFixed(
					2,
					Decimal.ROUND_DOWN
				)
			).toNumber()
		},
		getRowClass({ row, column, rowIndex, columnIndex }) {
			if (rowIndex === 0) {
				return 'background:#EFEFEF'
			} else {
				return ''
			}
		},
		/**
		 * 增加契约条件
		 */
		addRow() {
			// 如果不是自定义政策，那么契约条件数量不能大于最低契约条件数量
			if (
				!this.customForm &&
				this.tableForm.length >= this.rebateRatioList.length
			) {
				return this.$message.warning(
					this.$t('common.components.add_condition').replace(
						'xx',
						this.rebateRatioList.length
					)
				)
			}

			this.tableForm.push(
				Object.assign({}, templateData[this.contractType])
			)
		},

		/**
		 * 删除当前条件
		 */
		deleteRow(index) {
			this.tableForm.splice(index, 1)
			this.filterAvailableSelect()
		},

		// ----------------- 表单校验 -----------------
		checkRebateRatioAvailability() {
			const resultArr = []
			if (this.tableForm.length) {
				const rebateRateArr = this.tableForm.map(
					(item) => item.rebateRate
				)
				const originalArr = this.rebateRatioList.map(
					(item) => item.rebateRatio
				)
				rebateRateArr.forEach((v) => {
					if (!originalArr.includes(v)) {
						resultArr.push(v)
					}
				})
			}
			return resultArr
		},

		/**
		 * 模板中的rules自定义校验方法
		 */
		validateTableForm(field, fieldName, index) {
			return (rule, value, callback) => {
				if (!value && value !== 0) {
					callback(
						new Error(
							`${this.$t('common.please_enter')}${
								['vi_VN', 'en_US'].includes(this.$i18n.locale)
									? ` ${fieldName} `
									: fieldName
							}`
						)
					)
				} else {
					this.handleValidation(field, index, callback)
					callback()
				}
			}
		},

		/**
		 * 校验逻辑
		 */
		handleValidation(field, index, callback) {
			const currentForm = this.tableForm
			if (currentForm.length >= 1) {
				let rebateRatioItem
				// 如果不是自定义表单，需要匹配最低契约条件，并进行比对
				if (!this.customForm) {
					rebateRatioItem = this.rebateRatioList.find(
						(item) =>
							item.rebateRatio === currentForm[index].rebateRate
					)
				}
				// 最低契约条件值
				const minValue = rebateRatioItem
					? rebateRatioItem[field]
					: undefined

				let prev
				if (currentForm[index - 1]) {
					prev = currentForm[index - 1][field]
				}

				let current
				if (currentForm[index]) {
					current = currentForm[index][field]
				}

				let next
				if (currentForm[index + 1]) {
					next = currentForm[index + 1][field]
				}

				if (field === this.rebateRateFieldName) {
					if (this.maxCustomRatio && current > this.maxCustomRatio) {
						callback(
							new Error(
								`${this.$t('common.components.no_more_than')}${
									this.maxCustomRatio
								}`
							)
						)
					}

					if (current <= prev) {
						callback(
							new Error(this.$t('common.components.more_than'))
						)
					}

					if (current >= next) {
						callback(
							new Error(this.$t('common.components.less_than'))
						)
					}
				} else {
					if (minValue && current < minValue) {
						callback(
							new Error(
								`${this.$t(
									'common.components.no_less_than'
								)}${minValue}`
							)
						)
					}

					if (current < prev) {
						callback(
							new Error(
								this.$t('common.components.no_less_than_data')
							)
						)
					}

					if (current > next) {
						callback(
							new Error(
								this.$t('common.components.no_more_than_data')
							)
						)
					}
				}
			}
		},

		// ----------------- 导入保存模板弹窗 -----------------
		openImportDialog() {
			this.template.importDialog = true
			this.getContractTemplateList()
		},
		/**
		 * 获取契约模板分页数据
		 */
		getContractTemplateList() {
			this.template.loading = true
			this.$api
				.getContractTemplateListAPI({
					templateType: this.contractType,
					pageNum: this.template.paginate.pageNum,
					pageSize: this.template.paginate.pageSize,
					policyTypeConfigId: this.topForm.policyType.id,
					merchantId: this.topForm.merchantId
				})
				.then((res) => {
					if (res?.code === 200) {
						const { records, total } = res.data || {}
						this.template.templateArr = records || []
						this.template.paginate.total = total || 0
					}
					this.template.loading = false
				})
				.catch(() => (this.template.loading = false))
		},

		/**
		 * 导入模板方法
		 */
		importTemplate() {
			this.$refs.importTemplate.validate((valid) => {
				if (valid) {
					this.loadScaleListOnImport()
				}
			})
		},
		/**
		 * 获取当前契约模板id对应的比例配置
		 */
		loadScaleListOnImport() {
			this.template.loading = true
			const params = {
				contractId: this.template.importFormData.templateId,
				contractType: this.contractType,
				dataSourceType: 1,
				merchantId: this.topForm.merchantId
			}
			this.$api
				.getContractScaleListAPI(params)
				.then((res) => {
					this.template.loading = false

					if (!res.data.length) {
						return this.$message.error(
							this.$t('common.components.rate_config')
						)
					}
					let availableArr = []

					// 如果是非总代，需要过滤出大于上级最大比例的数据
					if (this.topForm.signProxyLevel > 0) {
						availableArr = res.data.filter(
							(item) => item.rebateRate > this.parentMaxRebateRate
						)
					}
					// 如果过滤得到了数据，那么提示
					if (availableArr.length) {
						return this.$message.error(
							this.$t('common.components.rate_agent')
						)
					}
					// 将组装好的数据覆盖到当前契约的数组中
					this.tableForm = this.assignTemplateData(res.data)
					this.filterAvailableSelect()

					this.template.importDialog = false
				})
				.catch(() => (this.template.loading = false))
		},

		/**
		 * 重新组装模板数据
		 */
		assignTemplateData(data) {
			const arr = []
			let obj
			data.forEach((item) => {
				if (this.contractType === 1) {
					obj = {
						rebateRate: this._decimalToMul(item.rebateRate),
						netAmount: item.netAmount,
						validBetAmount: item.validBetAmount,
						activeUsers: item.activeUsers,
						effecactiveUsers: item.effecactiveUsers,
						monthAddActiveCount: item.monthAddActiveCount
					}
					arr.push(obj)
				} else {
					obj = {
						rebateRate: this._decimalToMul(item.rebateRate),
						validBetAmount: item.validBetAmount,
						activeUsers: item.activeUsers,
						effecactiveUsers: item.effecactiveUsers
					}
					arr.push(obj)
				}
			})
			return arr
		},
		/**
		 * 过滤当前契约数组和比例列表的数据
		 */
		filterAvailableSelect(sort = false) {
			const selectedArr = []
			this.tableForm.forEach((item) => {
				if (item.rebateRate) selectedArr.push(item.rebateRate)
			})
			// 判断当前比例列表的值是否被选中，选中禁用未选中不禁用
			this.rebateRatioList.forEach((v) => {
				if (selectedArr.includes(v.rebateRatio)) {
					v.disabled = true
				} else {
					v.disabled = false
				}
			})
			if (sort) {
				this.tableForm.sort((a, b) => {
					return a.rebateRate - b.rebateRate
				})
			}
		},

		/**
		 * 重新赋值契约比例条件对应的字段
		 */
		assignRebateRatioData(item) {
			item.rebateRatio = this._decimalToMul(item.rebateRatio)
			item.netAmount = item.gameLoss
			item.validBetAmount = item.gameFlow
			item.activeUsers = item.monthActiveCount
			item.effecactiveUsers = item.monthEffectiveActiveCount
		},

		/**
		 * 获取最低契约数据
		 * type 调用时传入的契约类型
		 * @return Promise
		 */
		getRebateRatioList() {
			// this.$emit('update:loading', true)
			this.template.loading = true
			const params = {
				contractType: this.contractType
			}
			if (this.topForm) {
				params.signProxyName = this.topForm.signProxyName
				params.policyTypeConfigId = this.topForm.policyType.id
				params.merchantId = this.topForm.merchantId
			}
			return new Promise((resolve, reject) => {
				this.$api
					.queryRebateRatioAPI(params)
					.then((res) => {
						this.rebateRatioList = res.data?.contractConfigs || []
						this.parentMaxRebateRate = res.data?.rebateRatioMax
						if (this.topForm?.signProxyLevel > 0) {
							this.rebateRatioList = this.rebateRatioList.filter(
								(item) =>
									item.rebateRatio <= this.parentMaxRebateRate
							)
						}
						this.rebateRatioList.forEach((item) => {
							this.assignRebateRatioData(item)
							item.disabled = false
						})

						this.filterAvailableSelect()
						// this.$emit('update:loading', false)
						this.template.loading = false
						resolve()
					})
					.catch((v) => {
						this.rebateRatioList = []
						// this.$emit('update:loading', false)
						this.template.loading = false
					})
			})
		},
		/**
		 * 打开保存模板弹窗
		 */
		openSaveDialog() {
			this.template.saveDialog = true
		},

		/**
		 * 保存模板
		 */
		saveTemplate() {
			if (!this.tableForm.length) {
				return this.$confirm(
					this.$t('common.components.need_one'),
					this.$t('common.components.tip'),
					{
						confirmButtonText: this.$t('common.confirm'),
						showCancelButton: false,
						type: 'warning'
					}
				)
			}
			const validateArr = [
				this.validForm(this.$refs['saveTemplate']),
				this.validForm(this.$refs['tableForm'])
			]
			Promise.all(validateArr)
				.then(() => {
					this.template.loading = true
					const rebateContractList = JSON.parse(
						JSON.stringify(this.tableForm)
					)
					rebateContractList.forEach((item) => {
						item.rebateRate = this._decimalToDiv(item.rebateRate)
					})
					const params = {
						templateType: this.contractType,
						templateName: this.template.saveFormData.templateName,
						templateDes: this.template.saveFormData.templateDes,
						policyTypeConfigId: this.topForm.policyType.id,
						merchantId: this.topForm.policyType.merchantId,
						rebateContractList: rebateContractList
					}
					this.$api
						.saveContractTemplateAPI(params)
						.then((res) => {
							this.$message.success(
								this.$t('common.save_success')
							)
							this.template.loading = false
							this.template.saveDialog = false
						})
						.catch(() => {
							this.template.loading = false
						})
				})
				.catch(() => {})
		},

		/**
		 * 表单校验
		 */
		validForm(ref) {
			return new Promise((resolve, reject) => {
				ref?.validate((valid) => {
					if (valid) {
						resolve()
					} else {
						reject()
					}
				})
			})
		},

		/**
		 * 关闭弹窗时
		 */
		closeDialog(val) {
			this.$refs[val].resetFields()
		},

		/**
		 * 有政策类型时选择比例时
		 */
		onSelected(ratio, index) {
			this.assignRebateData(ratio, index)
			this.filterAvailableSelect(true)
			// this.validateAll()
		},

		/**
		 * 分配最低比例数据
		 */
		assignRebateData(ratio, index) {
			const rebateRatioItem = this.rebateRatioList.find(
				(item) => item.rebateRatio === ratio
			)
			const element = this.tableForm[index]
			if (this.contractType === 1) {
				element.netAmount = rebateRatioItem.gameLoss
				element.validBetAmount = rebateRatioItem.gameFlow
				element.activeUsers = rebateRatioItem.monthActiveCount
				element.effecactiveUsers =
					rebateRatioItem.monthEffectiveActiveCount
				element.monthAddActiveCount =
					rebateRatioItem.monthAddActiveCount
			} else {
				element.validBetAmount = rebateRatioItem.gameFlow
				element.activeUsers = rebateRatioItem.monthActiveCount
				element.effecactiveUsers =
					rebateRatioItem.monthEffectiveActiveCount
			}
		},
		validateAll() {
			const formName =
				this.templateType === '0' ? 'tableForm1' : 'tableForm2'
			this.$refs[formName].validate((valid) => {})
		},
		validateRebate(fieldName, index) {
			return (rule, value, callback) => {
				if (!value) {
					callback(
						new Error(
							`${this.$t('common.please_choose')}${fieldName}`
						)
					)
				} else {
					const rebateRatioItem = this.rebateRatioList.find(
						(item) =>
							item.rebateRatio ===
							this.tableForm[index].rebateRate
					)
					if (!rebateRatioItem) {
						callback(
							new Error(this.$t('common.components.reselect'))
						)
					} else {
						this.handleValidation(
							this.rebateRateFieldName,
							index,
							callback
						)
						callback()
					}
				}
			}
		},
		_handleSizeChange(value) {
			this.template.paginate.pageNum = 1
			this.template.paginate.pageSize = value
			this.getContractTemplateList()
		},
		_handleCurrentChange(value) {
			this.template.paginate.pageNum = value
			this.getContractTemplateList()
		},
		_decimalToDiv(val, y) {
			return val * 1 === 0 ? 0 : new Decimal(val).div(y || 100).toNumber()
		},
		_decimalToMul(val) {
			return val * 1 === 0 ? 0 : new Decimal(val).mul(100).toNumber()
		},
		getWidth(value, scale = 1.25) {
			if (this.$i18n.locale === 'zh_CN') {
				return value
			}
			if (typeof value !== 'object' && value) {
				const number = String(value).match(/\d+/)
				return typeof value === 'number'
					? +String(value).replace(/\d+/, number * scale)
					: String(value).replace(/\d+/, number * scale)
			}
		}
	}
}
</script>

<style lang="scss" scoped>
.table-wrapper {
	>>> .el-form-item__error {
	}
}
.operate-wrapper {
	display: flex;
	position: relative;
	height: 50px;
	align-items: center;
	.template {
		width: 150px;
	}
	.add {
		position: absolute;
		right: 30px;
	}
}

.en_US {
	.table-wrapper {
		::v-deep .el-form-item {
			margin-bottom: 18px;
		}
	}
}
</style>
